<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
    <title>咨询【${userid}|${username}】</title>
    <meta name="referrer" content="no-referrer" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 引用小图标 -->
    <link href="<%=request.getContextPath()%>/js/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"
          type="text/css" media="screen,print" />
    <!-- 添加jQuery -->
    <script src="<%=request.getContextPath()%>/js/jquery-3.3.1.min.js"></script>
    <!-- 添加BootStrap -->
    <script src="<%=request.getContextPath()%>/js/bootstrap-4.6.0/js/popper.min.js"
            type="text/javascript"></script>
    <link href="<%=request.getContextPath()%>/js/bootstrap-4.6.0/css/bootstrap.min.css" rel="stylesheet"
          type="text/css" media="screen,print" />
    <script src="<%=request.getContextPath()%>/js/bootstrap-4.6.0/js/bootstrap.min.js"
            type="text/javascript"></script>
    <!-- EasyUI -->
    <script type="text/javascript"
            src="<%=request.getContextPath()%>/js/jquery-easyui-1.8.8/jquery.easyui.min.js"></script>
    <script type="text/javascript"
            src="<%=request.getContextPath()%>/js/jquery-easyui-1.8.8/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript"
            src="<%=request.getContextPath()%>/js/jquery-easyui-1.8.8/plugins/jquery.datagrid.js"></script>
    <link href="<%=request.getContextPath()%>/js/jquery-easyui-1.8.8/themes/gray/easyui.css" rel="stylesheet"
          type="text/css" media="screen,print" />

    <!-- cookie操作工具 -->
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.cookie.js"></script>

    <!-- 添加平台公用js css -->
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/z.js" charset="UTF-8"></script>
    <link href="<%=request.getContextPath()%>/js/z.css" rel="stylesheet" type="text/css" media="screen,print" />

    <!-- 处理不同浏览器采集视频方法名不相同问题 -->
    <script type="text/javascript" src="<%=request.getContextPath()%>/js/webrct/adapter.js"></script>
    <input type="hidden" id="now_user_zid" value="${userid}">
    <input type="hidden" id="now_user_name" value="${username}">
    <input type="hidden" id="isMSN" value="${isMSN}">
    <input type="hidden" id="serverip" value="${serverip}">
    <input type="hidden" id="isSSL" value="${isSSL}">
    <input type="hidden" id="ice_url" value="${ice_url}">
    <input type="hidden" id="ice_username" value="${ice_username}">
    <input type="hidden" id="ice_password" value="${ice_password}">
    <script type="text/javascript">
        //websocket对象
        var ws = null;
        //本地视频流
        var localStream;
        //远端视频流
        var remoteStream;
        //本机RtcPeerConnection
        var pc = null;
        var offer = null;
        var answer = null;

        //用户ID
        var now_user_zid = '${userid}';
        var username = '${username}';
        //服务地址
        var serverip = $("#serverip").val();
        //是否启用ssh
        var isSSL = $("#isSSL").val();
        $(document).ready(function () {
            $('#message_windows').window('maximize');//最大化
            init_socket();
        });

        function init_socket() {
            if (!window.WebSocket) {
                alertMessager('您的浏览器不支持WebSocket');
            } else {
                var HTTPHEAD = 'ws';
                if (isSSL == 'true') {
                    HTTPHEAD = "wss";
                }
                //var now_user_zid = $('#now_user_zid').val();
                var socket_server_url = HTTPHEAD + '://' + serverip + '/zsocket?userid=' + now_user_zid+'&username='+username;
                ws = new WebSocket(socket_server_url);
                //链接成功事件
                ws.onopen = function () {
                    console.log(now_user_zid + "已连接websocket");
                }
                ws.onclose = function (e) {
                    console.log(now_user_zid + '已断开websocket|执行重新连接');
                    setTimeout('init_socket()',5000);
                    init_socket();
                }
                ws.onerror = function (e) {
                    console.log(now_user_zid + 'websocket连接出错|' + e);
                    setTimeout('init_socket()',5000);
                    init_socket();
                }

                //接收到信息
                ws.onmessage = function (obj) {
                    var ms = $.parseJSON(obj.data);
                    if ('usertouser' == ms.data.command_type) {
                        //显示消息
                        printMsg(obj.data);
                    } else if ('user_on_line' == ms.data.command_type) {
                        var userid = $("#now_user_zid").val();
                        var fromuserid = ms.data.fromuserid;
                        var fromusername = decodeURIComponent(ms.data.fromusername);
                        if (userid != fromuserid) {

                            var buttonname = '';
                            var buttonid = 'message_user_' + fromuserid;
                            if (isNotNull(fromusername)) {
                                alertMessager(fromusername + " 已上线")
                                buttonname = fromusername;
                            } else {
                                alertMessager(fromuserid + " 已上线")
                                buttonname = fromuserid;
                            }
                            //console.log(fromuserid+" 上线")
                            //RefreshMessagesList();

                            if ($('#' + buttonid).length <= 0) {
                                var button_html = '<button id="message_user_' + fromuserid + '" type="button" class="btn btn-success btn-block" onclick="OpenMessageWindows(\'' + fromuserid + '\',\'' + fromusername + '\')">' + buttonname + '</button>';
                                $('#UserMessagesList').append(button_html);
                            }
                        }
                    } else if ('user_off_line' == ms.data.command_type) {
                        var userid = $("#now_user_zid").val();
                        var fromuserid = ms.data.fromuserid;
                        var fromusername = ms.data.fromusername;
                        if (userid != fromuserid) {
                            if (isNotNull(fromusername)) {
                                alertMessager(fromusername + " 已下线")
                            } else {
                                alertMessager(fromuserid + " 已下线")
                            }
                            //console.log(fromuserid+" 下线")
                            //RefreshMessagesList();
                            var buttonid = 'message_user_' + fromuserid;
                            $('#' + buttonid).remove();
                        }
                    } else if ('audio_apply' == ms.data.command_type) {
                        //播放来电提示音
                        tel_audio();
                        printMsg(obj.data);
                    } else if ('audio_close' == ms.data.command_type) {
                        call_windows_close(false);
                    } else if ('audio_apply_yes' == ms.data.command_type) {
                        printMsg(obj.data);

                    } else if ('audio_apply_no' == ms.data.command_type) {
                        printMsg(obj.data);
                    } else if ('video_apply' == ms.data.command_type) {
                        //播放来电提示音
                        tel_audio();
                        printMsg(obj.data);
                        var userid = $("#now_user_zid").val();
                        if (userid === ms.data.touserid) {
                            console.log(ms.data.fromuserid + '申请和您进行视频通话');
                        }
                    } else if ('video_close' == ms.data.command_type) {
                        call_windows_close(false);
                    } else if ('video_apply_yes' == ms.data.command_type) {
                        //显示信息
                        printMsg(obj.data);
                        var userid = $("#now_user_zid").val();
                        if (userid === ms.data.touserid) {
                            console.log(ms.data.fromuserid + '同意和您进行视频通话,开始建立连接');
                            //创建RTCPeerConnection
                            CreateRTCPeerConnection(true, '');
                            //创建createOffer
                            createOffer(1, 1, 'webrtc_offer');
                        }
                    } else if ('video_apply_no' == ms.data.command_type) {
                        printMsg(obj.data);
                    } else if ('webrtc_offer' == ms.data.command_type) {
                        var userid = $("#now_user_zid").val();
                        if (userid === ms.data.touserid) {
                            offer = JSON.parse(ms.data.msg);
                            console.log(ms.data.fromuserid + '发给您的offer信息:');
                            //console.log(offer);

                            //setRemoteDescription
                            console.log('接收Offer | 执行setRemoteDescription');
                            pc.setRemoteDescription(new RTCSessionDescription(offer));

                            //创建createOffer
                            createAnswer(1, 1, 'webrtc_answer');
                        }
                    } else if ('webrtc_answer' == ms.data.command_type) {
                        var userid = $("#now_user_zid").val();
                        if (userid === ms.data.touserid) {
                            answer = JSON.parse(ms.data.msg);
                            console.log(ms.data.fromuserid + '发给您的answer信息:');
                            //console.log(answer);

                            //setRemoteDescription
                            console.log('接收Answer | 执行setRemoteDescription');
                            pc.setRemoteDescription(new RTCSessionDescription(answer));

                        }

                    } else if ('webrtc_candidate' == ms.data.command_type) {

                        var userid = $("#now_user_zid").val();
                        if (userid != ms.data.fromuserid) {
                            if (pc) {
                                var ic = JSON.parse(ms.data.msg);
                                //console.log('调用webrtc_candidate')
                                //console.log(ic)
                                var candidate = new RTCIceCandidate({
                                    sdpMLineIndex: ic.label,
                                    candidate: ic.candidate
                                })
                                console.log("fromuser:" + ms.data.fromuserid + "发送candidate| 执行addIceCandidate");
                                pc.addIceCandidate(candidate);
                            } else {
                                console.log("fromuser:" + ms.data.fromuserid + "发送candidate| 执行addIceCandidate|RtcPeerConnection未创建");
                            }
                        }

                    } else if ('system_message' == ms.data.command_type) {
                        alert(ms);
                    } else if ('group_message' == ms.data.command_type) {

                    } else if ('e_message' == ms.data.command_type) {
                        var e_msg = ms.data.msg;
                        alertErrorMessager(e_msg);
                    }
                };
                // 关闭页面时候关闭ws
                window.addEventListener("beforeunload", function (event) {
                    ws.close();
                });

                // ws.addEventListener('open', function () {
                //     //发送用户上线通知
                //     SendUserOnLine();
                // });

                if (isNull(ws.onopen)) {
                    //未成功链接WebSocket就关闭即时通讯列表
                    $('#zmain_easyui_layout').layout('remove', 'east');
                } else {

                }
            }
        }

        /**
         * 播放来电提示音
         */
        function tel_audio() {
            var audio = document.getElementById('tel_audio');
            if (audio !== null) {
                //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
                if (audio.paused) {
                    audio.play();//audio.play();// 这个就是播放
                } else {
                    audio.pause();// 这个就是暂停
                }
            }
        }


        //发送用户上线通知
        function SendUserOnLine() {
            var userid = $("#now_user_zid").val();
            var username = $("#now_user_name").val();
            //创建JSON对象
            var msgObj = {
                fromuserid: userid,
                fromusername: encodeURIComponent(username),
                command_type: 'user_on_line'
            };
            //发送消息
            ws.send(JSON.stringify(msgObj));
        }

        /**
         * 刷新消息列表
         */
        function RefreshMessagesList() {
            var session_userid = $("#now_user_zid").val();
            $.ajax({
                type: "GET",
                url: 'GetUserMessageList?touserid=' + session_userid,
                success: function (data) {
                    if (data.code == 'SUCCESS') {
                        $('#UserMessagesList').empty();
                        var messages_length = data.data.length;
                        for (var i = 0; i < messages_length; i++) {
                            var messageinfo = data.data[i];
                            var userid = messageinfo.zid;
                            if (session_userid != userid) {
                                var username = messageinfo.user_name;
                                if (messageinfo.messagecount > 0) {
                                    username = username + '[' + messageinfo.messagecount + ']';
                                }
                                var buttoncss = 'btn btn-light btn-block';
                                if (messageinfo.isonline == 0) {
                                    buttoncss = 'btn btn-success btn-block';
                                }
                                var button_html = '<button id="message_user_' + userid + '" type="button" class="' + buttoncss + '" onclick="OpenMessageWindows(\'' + userid + '\',\'' + messageinfo.user_name + '\')">' + username + '</button>';
                                $('#UserMessagesList').append(button_html);
                            }
                        }

                    }
                }
            });
        }





        /**
         * 根据信息类型，显示不同信息形态
         * @param r_text
         */
        function printMsgText(r_text) {
            var text = "";
            var r = $.parseJSON(r_text);
            var userid = $("#now_user_zid").val();
            var fromuserid = r.data.fromuserid;
            var fromusername = decodeURIComponent(r.data.fromusername);
            var touserid = r.data.touserid;
            var tousername = decodeURIComponent(r.data.tousername);
            var command_type = r.data.command_type;
            var msgtype = r.data.msgtype;
            var msg = decodeURIComponent(r.data.msg);
            var sendtime = r.data.sendtime;

            if ('usertouser' == command_type) {
                if (msgtype === '1') {
                    text = '<img src="' + msg + '" onclick="lookupImg2(\'' + msg + '\')" class="img-thumbnail">';
                } else {
                    text = msg;
                }
            } else if ('audio_apply' == command_type) {
                if (userid === fromuserid) {
                    text = "您已经向" + tousername + "发起语音通话请求，连接中";
                } else if (userid === touserid) {
                    text = fromusername + "请求与您进行语音通话。";
                    text = text + '<button type="button" onclick="audio_apply_yes(\'' + fromuserid + '\')" class="btn btn-link">同意</button>,';
                    text = text + '<button type="button" onclick="audio_apply_no(\'' + fromuserid + '\')" class="btn btn-link">不同意</button>';
                } else {
                    text = "发起语音通话异常";
                }
            } else if ('video_apply' == command_type) {
                if (userid === fromuserid) {
                    text = "您已经向" + tousername + "发起视频通话请求，连接中";
                } else if (userid === touserid) {
                    text = fromusername + "请求与您进行视频通话。"
                    text = text + '<button type="button" onclick="video_apply_yes(\'' + fromuserid + '\')" class="btn btn-link">同意</button>,';
                    text = text + '<button type="button" onclick="video_apply_no(\'' + fromuserid + '\')" class="btn btn-link">不同意</button>';
                } else {
                    text = "发起视频通话异常";
                }
            } else if ('audio_apply_no' == command_type) {
                if (userid === fromuserid) {
                    text = "您拒绝了" + tousername + "的通话申请。"
                } else if (userid === touserid) {
                    text = fromusername + "拒绝了您的通话申请";
                }
            } else if ('video_apply_no' == command_type) {
                if (userid === fromuserid) {
                    text = "您拒绝了" + tousername + "的视频申请。"
                } else if (userid === touserid) {
                    text = fromusername + "拒绝了您的视频申请";
                }
            } else if ('audio_apply_yes' == command_type) {
                if (userid === fromuserid) {
                    text = "您同意了" + tousername + "的通话申请。"
                } else if (userid === touserid) {
                    text = fromusername + "同意了您的通话申请";
                }
            } else if ('video_apply_yes' == command_type) {
                if (userid === fromuserid) {
                    text = "您同意了" + tousername + "的视频申请。"
                } else if (userid === touserid) {
                    text = fromusername + "同意了您的视频申请";
                }
            } else {
                text = msg;
            }
            return text;
        }

        /**
         * 显示消息
         */
        function printMsg(r_text) {
            if (isNotNull(r_text)) {
                var r = $.parseJSON(r_text);
                var userid = $("#now_user_zid").val();
                var fromuserid = r.data.fromuserid;
                var fromusername = decodeURIComponent(r.data.fromusername);
                var touserid = r.data.touserid;
                var tousername = decodeURIComponent(r.data.tousername);
                var command_type = r.data.command_type;
                var msgtype = r.data.msgtype;
                var msg = decodeURIComponent(r.data.msg);
                var sendtime = r.data.sendtime;


                //保存聊天记录到Cookie
                var message_cookieid = 'message_cookieid_' + fromuserid + '_' + touserid;
                var message_cookie_obj = {
                    fromuserid: fromuserid,
                    fromusername: fromusername,
                    touserid: touserid,
                    tousername: tousername,
                    sendtime: sendtime,
                    msg: msg
                };
                var old_message_cookie = getCookie(message_cookieid);
                var new_message_cookie = old_message_cookie + '☆' + JSON.stringify(message_cookie_obj);
                setCookie(message_cookieid, new_message_cookie);


                //判读聊天窗口是否打开
                var isopen = $('#message_windows').parent().css('display');
                if (isopen == 'none') {
                    //未打开

                    //发送右下角消息提醒
                    if (userid == touserid) {
                        var msgHTML = '		<div class="msgbox">';
                        msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
                        msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
                        msgHTML = msgHTML + '		</div>';
                        alertMessager('<a href="javascript:void(0);" onclick="OpenMessageWindows(\'' + fromuserid + '\',\'' + fromusername + '\')">' + msgHTML + '</a>');
                    }

                    //更新用户头像后面消息数量
                    UpdateMessageCount(fromuserid);

                }


                //将消息显示在对应 用户消息框中
                if (userid == fromuserid) {
                    //创建消息
                    var msgHTML = '		<div class="msgbox">';
                    msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
                    msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
                    msgHTML = msgHTML + '		</div>';
                    $('#msgboxlist_' + touserid).append(msgHTML);

                    //控制滚动条到最底部
                    var scrollHeight = $('#msgboxlist_' + touserid).prop("scrollHeight");
                    $('#msgboxlist_' + touserid).animate({ scrollTop: scrollHeight }, 400);
                } else {

                    //判读是否已经建立了发信人消息框
                    if (!$('#MessageTab').tabs('exists', fromusername)) {
                        var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
                        tabHTML = tabHTML + '	<div id="msgboxlist_' + fromuserid + '" data-options="region:\'center\'" style="padding:10px;">';
                        tabHTML = tabHTML + '	</div>';
                        tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
                        tabHTML = tabHTML + '		<textarea id="msg_' + fromuserid + '" style="width: 100%;height: 100%;resize:none;border:none;"></textarea>';
                        tabHTML = tabHTML + '		<button class="btn btn-light " onclick="OpenGetImg()" style="position:absolute;left:5px;bottom:5px;"><i class="fa fa-image"></i></button>';
                        tabHTML = tabHTML + '		<button class="btn btn-light " onclick="AudioCall()" style="position:absolute;left:45px;bottom:5px;"><i class="fa fa-phone"></i></button>';
                        tabHTML = tabHTML + '		<button class="btn btn-light" onclick="VideoCall()" style="position:absolute;left:85px;bottom:5px;"><i class="fa fa-video-camera"></i></button>';
                        tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-send-o"></i> 发送</button>';
                        tabHTML = tabHTML + '	</div>';
                        tabHTML = tabHTML + '</div>';

                        $('#MessageTab').tabs('add', {
                            title: fromusername,
                            id: fromuserid,
                            content: tabHTML
                        });

                        //$('#MessageTab').tabs('select', fromusername);
                    } else {
                        var tab = $('#MessageTab').tabs('getSelected');
                        var title = tab.panel('options').title;
                        if (fromusername != title) {
                            //更新用户头像后面消息数量
                            UpdateMessageCount(fromuserid);
                        }
                    }

                    //创建消息
                    var msgHTML = '		<div class="msgbox">';
                    msgHTML = msgHTML + '			<div class="msgboxhead0">' + fromusername + ' ' + sendtime + '</div>';
                    msgHTML = msgHTML + '			<div class="msgboxtext">' + printMsgText(r_text) + '</div>';
                    msgHTML = msgHTML + '		</div>';
                    $('#msgboxlist_' + fromuserid).append(msgHTML);

                    //控制滚动条到最底部
                    var scrollHeight = $('#msgboxlist_' + fromuserid).prop("scrollHeight");
                    $('#msgboxlist_' + fromuserid).animate({ scrollTop: scrollHeight }, 400);
                }
            }
        }


        //更新用户头像后面消息数量
        function UpdateMessageCount(fromuserid) {
            $.ajax({
                type: "GET",
                async: true, //true为异步方法 false为同步方法
                url: 'getFromuserMessageCount?fromuserid=' + fromuserid,
                success: function (data) {
                    if (data.code == 'SUCCESS') {
                        $('#message_user_' + fromuserid).text(data.data);
                    }
                },
                error: function (data) {
                    parent.alertErrorMessager('ajax错误：' + data);
                }
            });
        }

        /**
         * 执行发送
         */
        function RunSend(obj) {
            if (ws.readyState === 1) {
                var r = ws.send(JSON.stringify(obj));
                console.log(r);
            } else {
                console.log(ws);
                init_socket();
                if (ws.readyState === 1) {
                    var r = ws.send(JSON.stringify(obj));
                    console.log(r);
                } else {
                    alertErrorMessager('与通信服务连接已断开，无法发送信息给服务器')
                }

            }
        }

        /**
         * 用户发送信息
         */
        function sendMessage() {
            var fromuserid = $("#now_user_zid").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            var msg = encodeURIComponent($('#msg_' + touserid).val());
            var msgtype = '0';//0是文本消息

            //创建JSON对象
            var msgObj = {
                fromuserid: fromuserid,
                fromusername:encodeURIComponent(username),
                touserid: touserid,
                command_type: 'usertouser',
                msgtype: msgtype,
                msg: msg
            };

            //发送消息
            RunSend(msgObj);


            //请空已发送信息
            $('#msg_' + touserid).val('');
            $('#msg_' + touserid).focus();

        }

        /**
         * 获取系统时间
         * @returns {string}
         */
        function getDateTime() {
            var myDate = new Date();
            var year = myDate.getFullYear(); //获取当前年
            var mon = myDate.getMonth() + 1; //获取当前月
            var date = myDate.getDate(); //获取当前日
            var h = myDate.getHours();//获取当前小时数(0-23)
            var m = myDate.getMinutes();//获取当前分钟数(0-59)
            var s = myDate.getSeconds();//获取当前秒
            return year + "-" + mon + "-" + date + " " + h + ":" + m + ":" + s;
        }

        /**
         * 打开聊天窗口
         */
        function OpenMessageWindows(fromuserid, fromusername) {
            $('#fromuserid').val('${zuser.zid}');
            $('#touserid').val(fromuserid);

            if (!$('#MessageTab').tabs('exists', fromusername)) {
                var tabHTML = '<div class="easyui-layout" data-options="fit:true">';
                tabHTML = tabHTML + '	<div id="msgboxlist_' + fromuserid + '" data-options="region:\'center\'" style="padding:10px;">';
                tabHTML = tabHTML + '	</div>';
                tabHTML = tabHTML + '	<div data-options="region:\'south\',split:true" style="position:relative;margin: 0px;padding: 0px;height: 150px;">';
                tabHTML = tabHTML + '		<textarea id="msg_' + fromuserid + '" style="width: 100%;height: 80%;resize:none;border:none;outline:none;margin-top:0px;margin-bottom:0px;"></textarea>';
                tabHTML = tabHTML + '		<button class="btn btn-light " onclick="OpenGetImg()" style="position:absolute;left:5px;bottom:5px;"><i class="fa fa-image"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light " onclick="AudioCall()" style="position:absolute;left:45px;bottom:5px;"><i class="fa fa-phone"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light" onclick="VideoCall()" style="position:absolute;left:85px;bottom:5px;"><i class="fa fa-video-camera"></i></button>';
                tabHTML = tabHTML + '		<button class="btn btn-light" onclick="sendMessage()" style="position:absolute;right:20px;bottom:5px;"><i class="fa fa-send-o"></i> 发送</button>';
                tabHTML = tabHTML + '	</div>';
                tabHTML = tabHTML + '</div>';

                $('#MessageTab').tabs('add', {
                    title: fromusername,
                    id: fromuserid,
                    content: tabHTML
                });
            } else {
                $('#MessageTab').tabs('select', fromusername);
            }

            //设置焦点
            $('#msg_' + fromuserid).focus();

            //修改消息是否查看状态为以查看
            UpdateIsOpen(fromuserid, fromusername);


            //判读指定用户聊天窗口是首着次打开，如果是首次打开，加载cookie中的历史信息到当前窗口
            var touserid = $("#now_user_zid").val();
            var message_cookieid = 'message_cookieid_' + fromuserid + '_' + touserid;
            if ($('#msgboxlist_' + fromuserid).children().length == 0) {
                var old_message_cookie = getCookie(message_cookieid);
                var messageArray = old_message_cookie.split('☆');
                for (var i = 0; i < messageArray.length; i++) {
                    var message_r_text = messageArray[i];
                    if (isNotNull(message_r_text)) {
                        var r = $.parseJSON(message_r_text);
                        var fromusername = r.fromusername;
                        var msg = r.msg;
                        var sendtime = r.sendtime;
                        if (isNotNull(fromusername)) {
                            //创建消息
                            var msgHTML = '		<div class="msgbox">';
                            if (touserid == r.fromuserid) {
                                msgHTML = msgHTML + '			<div class="msgboxhead1">' + fromusername + ' ' + sendtime + '</div>';
                            } else {
                                msgHTML = msgHTML + '			<div class="msgboxhead0">' + fromusername + ' ' + sendtime + '</div>';
                            }

                            msgHTML = msgHTML + '			<div class="msgboxtext">' + msg + '</div>';
                            msgHTML = msgHTML + '		</div>';
                            $('#msgboxlist_' + fromuserid).append(msgHTML);
                        }

                    }

                }
            }

            //直接Open不显示新消息，需要动一下窗口，就能显示，怀疑这块是一个easyui的bug
            $('#message_windows').window('open');//打开窗口
            $('#message_windows').window('collapse');//折叠
            $('#message_windows').window('expand');//展开

        }

        //修改消息是否查看状态为以查看
        function UpdateIsOpen(fromuserid, fromusername) {
            $.ajax({
                type: "get",
                async: true, //true为异步方法 false为同步方法
                url: 'UpdateIsOpen?fromuserid=' + fromuserid,
                success: function (data) {
                    if (data.code == 'SUCCESS') {
                        $('#message_user_' + fromuserid).text(fromusername);
                    }
                },
                error: function (data) {
                    parent.alertErrorMessager('ajax错误：' + data);
                }
            });
        }

        /**
         * 关闭聊起页
         */
        function CloseMessageWindows(touserid, tousername) {
            $('#MessageTab').tabs('close', tousername);
            var tab = $('#MessageTab').tabs('getSelected');
            var index = $('#MessageTab').tabs('getTabIndex', tab);
            if (index < 0) {
                //关闭windows窗口
                $('#message_windows').window('close');
            }
        }

        /**
         * 打开图片选择页面
         * @constructor
         */
        function OpenGetImg() {
            var width = 400;
            var height = 250;
            var iTop = (window.screen.availHeight - 30 - height) / 2;//获得窗口的垂直位置;
            var iLeft = (window.screen.availWidth - 10 - width) / 2;//获得窗口的水平位置;
            var url = 'im_getimg';
            window.open(url, '文件上传', 'width=' + width + ',height=' + height + ',location=no,menubar=no,status=no,toolbar=no, top=' + iTop + ', left=' + iLeft);
        }

        /**
         *
         * @constructor
         */
        function SendImg(urls) {
            var userid = $("#now_user_zid").val();
            var username = $("#now_user_name").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            //创建JSON对象
            var msgObj = {
                fromuserid: userid,
                fromusername: encodeURIComponent(username),
                touserid: touserid,
                command_type: 'usertouser',
                msgtype: 'img',
                msg: urls
            };
            //发送消息
            ws.send(JSON.stringify(msgObj));
        }

        /**
         * 即时通讯发起语音通话
         */
        function AudioCall() {
            //启动本地视频
            OpenLocalVideoCallBox(false, false, '');
            //申请视频通话
            SendMassage('audio_apply', '');
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('您申请与' + touserid + '进行语音通话');
        }

        /**
         * 即时通讯发起视频通话
         */
        function VideoCall() {
            //启动本地视频
            OpenLocalVideoCallBox(false, false, '');
            //申请视频通话
            SendMassage('video_apply', '');
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('您申请与' + touserid + '进行视频通话');
        }


        /**
         * 打开本地视频采集窗口
         * @constructor
         */
        function OpenLocalAudioCallBox(isCreateRTCPeerConnection, isAddStream) {
            var isopen = $('#local_call_windows').parent().css('display');
            if (isopen == 'none') {
                //未打开
                $('#local_call_windows').window('open');//打开窗口
                $('#local_call_windows').window('collapse');//折叠
                $('#local_call_windows').window('expand');//展开
            }

            //采集音视频设备数据,采集音频与视频，视频格式为320*600 试用于手机
            OpenUserMedia(true, false, isCreateRTCPeerConnection, isAddStream, messageType);

        }

        /**
         * 打开本地视频采集窗口
         * @constructor
         */
        function OpenLocalVideoCallBox(isCreateRTCPeerConnection, isAddStream, messageType) {
            var local_call_windows_isopen = $('#local_call_windows').parent().css('display');
            if (local_call_windows_isopen == 'none') {
                //未打开
                $('#local_call_windows').window('open');//打开窗口
                $('#local_call_windows').window('collapse');//折叠
                $('#local_call_windows').window('expand');//展开
            }

            //采集音视频设备数据,采集音频与视频，视频格式为320*600 试用于手机
            OpenUserMedia(true, { width: 320, height: 600 }, isCreateRTCPeerConnection, isAddStream, messageType);
        }

        /**
         * 打开用户音视频设备
         * audio:json/boolean 是否采集音频
         * video:json/boolean 是否采集视频 示例：{width: 320, height: 600 } 手机
         * isAddStream:是否同步推流
         */
        function OpenUserMedia(audio, video, isCreateRTCPeerConnection, isAddStream, messageType) {
            var userid = $("#now_user_zid").val();
            //var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            var getUserMedia = navigator.getUserMedia;
            if (isNotNull(getUserMedia)) {
                var constraints = { audio: audio, video: video };
                navigator.mediaDevices.getUserMedia(constraints).then(function (mediaStream) {
                    //本地流
                    localStream = mediaStream;

                    //是否同步创建链接
                    if (isCreateRTCPeerConnection) {
                        console.log(userid + '开始建立连接');
                        CreateRTCPeerConnection(isAddStream, messageType);
                    }

                    //将流显示出来
                    var localvideo = document.querySelector('video#localvideo');
                    localvideo.srcObject = mediaStream;


                }).catch(function (err) {
                    console.log('采集音视频设备信息出错');
                    console.log(err);
                });
            } else {
                console.log('浏览器不支持视频通话');
            }
        }


        //同意语音通话
        function audio_apply_yes(fromuserid) {
            //启动本地视频
            OpenLocalAudioCallBox(true, true, 'audio_apply_yes');

        }

        //拒绝语音通话
        function audio_apply_no(fromuserid) {
            var userid = $("#now_user_zid").val();
            var username = $("#now_user_name").val();
            //创建JSON对象
            var msgObj = {
                fromuserid: userid,
                fromusername: encodeURIComponent(username),
                touserid: fromuserid,
                command_type: 'audio_apply_no',
                msg: encodeURIComponent(username + '拒绝了您的通话申请')
            };
            //发送消息
            ws.send(JSON.stringify(msgObj));
        }

        //同意视频通话
        function video_apply_yes(fromuserid) {
            //启动本地视频
            OpenLocalVideoCallBox(true, true, 'video_apply_yes');
        }

        //拒绝视频通话
        function video_apply_no(fromuserid) {
            var userid = $("#now_user_zid").val();
            var username = $("#now_user_name").val();
            //创建JSON对象
            var msgObj = {
                fromuserid: userid,
                fromusername: encodeURIComponent(username),
                touserid: fromuserid,
                command_type: 'video_apply_no',
                msg: encodeURIComponent(username + '拒绝了您的视频申请')
            };
            //发送消息
            ws.send(JSON.stringify(msgObj));
        }


        /**
         * Createpc
         * @constructor
         * isAddStream 是否同步推流
         */
        function CreateRTCPeerConnection(isAddStream, messageType) {
            var userid = $("#now_user_zid").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('发起人：' + userid + ' | 接收人：' + touserid + '   | 方法名：CreateRTCPeerConnection');

            var config = {};
            var iceServers = [];
            var iceserver = {};
            iceserver.urls = $("#ice_url").val();
            iceserver.credential = $("#ice_username").val();
            iceserver.user = $("#ice_password").val();
            iceServers.push(iceserver);
            config.iceServers = iceServers;

            // var pcConfig = {
            //     'iceServers':[{
            //         'urls':'stun:coturn.merroix.com:3478',
            //         'credential':'merro',
            //         'user':'Merro1234'
            //     }]
            // }
            var iceServers = [];

            //创建连接
            pc = new RTCPeerConnection(config);

            //是否直接推送流
            if (isAddStream) {
                //将本地流向远程推送
                console.log('发起人：' + userid + ' - 开始推流');
                localStream.getTracks().forEach(track => {
                    console.log(userid + '-推送视频流')
                    pc.addTrack(track, localStream);
                });
            }

            //是否发送指令
            if (isNotNull(messageType)) {
                SendMassage(messageType, '');
            }

            //向远端发送信息
            pc.onicecandidate = (e) => {
                if (e.candidate) {
                    console.log("fromuser:" + userid + " 收到STUN服务器回调|e.candidate=" + e.candidate);
                    //发送信息给接收端
                    var msg = {
                        type: 'candidate',
                        label: e.candidate.sdpMLineIndex,
                        id: e.candidate.sdpMid,
                        candidate: e.candidate.candidate
                    };
                    SendMassage("webrtc_candidate", msg);
                }
            }

            //接收对方视频流，显示出来
            var remotevideo = document.querySelector('video#remotevideo');
            pc.ontrack = (e) => {
                remotevideo.srcObject = e.streams[0];
            }
        }


        /**
         * 创建协商信息
         */
        function createOffer(offerToRecieveAudio, offerToRecieveVideo, command_type) {
            var userid = $("#now_user_zid").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('发起人：' + userid + ' | 接收人：' + touserid + '   | 方法名：创建createOffer');

            if (pc) {
                //创建协商信息
                var offerOptions = {
                    offerToRecieveAudio: offerToRecieveAudio,
                    offerToRecieveVideo: offerToRecieveVideo
                }
                pc.createOffer(offerOptions).then(function (desc) {
                    console.log('根据Offer执行setLocalDescription')
                    pc.setLocalDescription(desc)
                    // console.log('createOffer==>desc');
                    // console.log(desc);
                    offer = desc.toJSON();
                    //发送视频通话请求,包括offer协商信息
                    SendMassage(command_type, offer);
                }).catch(function (err) {
                    console.log("创建视频协商信息出错");
                    console.log(err);
                });
            }
        }

        function createAnswer(offerToRecieveAudio, offerToRecieveVideo, command_type) {
            var userid = $("#now_user_zid").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('发起人：' + userid + ' | 接收人：' + touserid + '   | 方法名：创建createAnswer');
            pc.createAnswer().then(function (desc) {
                console.log('根据Answer执行setLocalDescription')
                pc.setLocalDescription(desc);
                // console.log('createAnswer==>desc');
                // console.log(desc);
                //发送协商信息
                SendMassage(command_type, desc);
            }).catch(function (err) {
                console.error('错误的协商信息');
                console.error(err);
            })
        }




        /**
         * 发送协商信息
         * @param desc
         * @constructor
         * 333333333333333
         */
        function SendMassage(command_type, desc) {
            var userid = $("#now_user_zid").val();
            var username = $("#now_user_name").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            var tousername = $('#MessageTab').tabs('getSelected').panel('options').title;
            //创建JSON对象
            var msgObj = {
                fromuserid: userid,
                fromusername:encodeURIComponent(username),
                touserid: touserid,
                tousername:encodeURIComponent(tousername),
                command_type: command_type,
                msg: desc
            };
            //发送消息
            ws.send(JSON.stringify(msgObj));
        }


        /**
         * 关闭RTCPeerConnection
         */
        function closeRTCPeerConnection() {
            var userid = $("#now_user_zid").val();
            var touserid = $('#MessageTab').tabs('getSelected').panel('options').id;
            console.log('发起人：' + userid + ' | 接收人：' + touserid + '   | 方法名：关闭RTCPeerConnection');
            if (pc) {
                pc.close();
                pc = null;
            }
        }

        /**
         * 结束视频
         */
        function call_windows_close(isSendCommand) {
            if (isSendCommand) {
                //发送结束视频命令
                SendMassage("video_close", "");
            }

            //关闭本地视频流
            var localvideo = document.querySelector('video#localvideo');
            if (isNotNull(localvideo)) {
                var localvideo_stream = localvideo.srcObject;
                if (isNotNull(localvideo_stream)) {
                    var localvideo_tracks = localvideo_stream.getTracks();
                    if (isNotNull(localvideo_tracks)) {
                        for (const track of localvideo_tracks) {
                            track.stop();
                        }
                        localvideo.srcObject = null;
                        localStream = null;
                    }
                }
            }

            //关闭远程视频流
            var remotevideo = document.querySelector('video#remotevideo');
            if (isNotNull(remotevideo)) {
                var remotevideo_stream = remotevideo.srcObject;
                if (isNotNull(remotevideo_stream)) {
                    var remotevideo_tracks = remotevideo_stream.getTracks();
                    if (isNotNull(remotevideo_tracks)) {
                        for (const track of remotevideo_tracks) {
                            track.stop();
                        }
                        remotevideo.srcObject = null;
                        remoteStream = null;
                    }
                }
            }

            //关闭连接
            closeRTCPeerConnection();

            //关闭窗口
            $('#local_call_windows').window('close');
        }
    </script>


</head>

<body>
<!-- 聊天窗口 -->
<div id="message_windows" class="easyui-window" title="消息管理" style="width:800px;height:500px"
     data-options="resizable:false,closable:false,closed:false,minimizable:false,maximizable:false,cache:false,collapsible:false">
    <div id="MessageTab" class="easyui-tabs" border="false" fit="true" tabPosition="left"></div>
</div>

<!-- 通话窗口 -->
<div id="local_call_windows" class="easyui-window" title="通话-本人" style="width:700px;height:700px"
     data-options="resizable:true,closable:false,closed:true,shadow:false,minimizable:false,maximizable:true,cache:false,collapsible:false">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'west'" style="width:50%;padding:10px">
            <video id="localvideo" autoplay playsinline></video>
        </div>
        <div data-options="region:'center'" style="width:50%;padding:10px">
            <video id="remotevideo" autoplay playsinline></video>
        </div>
        <div data-options="region:'south'" style="height:50px;">
            <button class="btn btn-danger btn-lg btn-block" onclick="call_windows_close(true)">结束视频</button>
        </div>
    </div>
</div>
</body>

</html>